package com.wyj.chat.websocket_chat.service.impl;

import com.wyj.chat.websocket_chat.dao.GroupMapper;
import com.wyj.chat.websocket_chat.pojo.Group;
import com.wyj.chat.websocket_chat.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by wyj on 2018/4/17
 */
@Service
@Transactional
public class GroupServiceImpl implements GroupService{

    @Autowired
    private GroupMapper groupMapper;

    @Override
    public List<String> getMemberList(String name) {
        List<String> list = new ArrayList<>();
        List<String> memberList = new ArrayList<>();
        String members = groupMapper.getMembers(name);
        if (StringUtils.isEmpty(members)) {
            return null;
        }
        if (members.contains(",")) {
            list = Arrays.asList(members.split(","));
        } else {
            list.add(members);
        }
        for (int i = 1; i < list.size(); i++) {
            memberList.add(list.get(i));
        }
        return memberList;
    }

    @Override
    public int createGroup(String name) {
        return groupMapper.createGroup(name);
    }

    @Override
    public int addGroup(String name, String userName) {
        String members = groupMapper.getMembers(name);
        String newMembers = members + "," + userName;
        return groupMapper.updateGroup(name,newMembers);
    }

    @Override
    public int leaveGroup(String name, String userName) {
        String members = groupMapper.getMembers(name);
        members = members.replace(","+userName, "");
        return groupMapper.updateGroup(name, members);
    }

    @Override
    public int isExitInGroup(String name, String userName) {
        String members = groupMapper.getMembers(name);
        if (members.contains(userName)) {
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public Group searchGroupByName(String name) {
        return groupMapper.searchGroupByName(name);
    }

    @Override
    public List<String> getGroupNameList(String members) {
        List<Group> allGroupList = groupMapper.getAllGroup();
        List<String> groupNameList = new ArrayList<>();
        for (int i = 0; i < allGroupList.size(); i ++) {
            if (allGroupList.get(i).getMembers().contains(members)) {
                groupNameList.add(allGroupList.get(i).getName());
            }
        }
        return groupNameList;
    }
}
